<template>
  <div>
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :wrapper-col="{ span: 6, offset: 9 }"
    >
      <a-form-item name="adminname">
        <a-input v-model:value="formState.adminname" placeholder="管理员账号"/>
      </a-form-item>
      <a-form-item name="password">
        <a-input type="password" v-model:value="formState.password" placeholder="管理员密码"/>
      </a-form-item>

      <a-form-item :wrapper-col="{ span: 6, offset: 9 }">
        <a-button type="primary" @click="onSubmit">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, toRaw } from 'vue'
import { loginFn } from '../../api/user'
import { useStore } from '../../store'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
export default defineComponent({
  setup () {
    const router = useRouter()
    const store = useStore()
    const formRef = ref()
    const formState = reactive({
      adminname: '',
      password: ''
    })
    const rules = {
      adminname: {
        required: true,
        message: '请输入管理员账户'
      },
      password: {
        required: true,
        message: '请输入密码'
      }
    }
    const onSubmit = () => {
      formRef.value
        .validate()
        .then(() => {
          console.log('values', formState, toRaw(formState))
          loginFn(formState).then(res => {
            console.log(res)

            if (res.code === '10005') {
              message.error('管理员未注册')
            } else if (res.code === '10003') {
              message.error('密码错误')
            } else {
              localStorage.setItem('adminname', formState.adminname)
              localStorage.setItem('token', res.data.token)
              localStorage.setItem('role', res.data.role)
              localStorage.setItem('isLogin', 'true')
              store.commit('user/CHANGE_ADMIN_NAME', formState.adminname)
              store.commit('user/CHANGE_TOKEN', res.data.token)
              store.commit('user/CHANGE_ROLE', res.data.role)
              store.commit('user/CHANGE_IS_LOGIN', true)
              router.push('/')
            }
          })
        })
        .catch((error: any) => {
          console.log('error', error)
        })
    }
    return {
      formRef,
      formState,
      rules,
      onSubmit
    }
  }
})
</script>
